package com.ququ.syb.business.withdraw.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Macro on 16/12/21.
 */
@Service
public class RabbitMQSender {

    private Logger logger = LoggerFactory.getLogger(RabbitMQSender.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ConnectionFactory connectionFactory;

    private final String EXCHANGE_NAME = "syb";


    public void send(String queueName,String message){
        send(queueName,message,null);
    }

    public void send(String queueName,String message,Long ttl){
        Connection connection = connectionFactory.createConnection();
        logger.debug("connection状态{},IP={}",connection.isOpen(),connectionFactory.getHost());
        Channel channel=null;
        try {

            channel = connection.createChannel(false);

            if(ttl != null){
                AMQP.BasicProperties basicProperties  = new AMQP.BasicProperties("text/plain", null, null, Integer.valueOf(2), Integer.valueOf(0), null, null, String.valueOf(ttl), null, null, null, null, null, null);
                logger.info("目标队列:{};发送内容:{}",queueName+",延时"+ttl,message );
                channel.basicPublish(EXCHANGE_NAME, queueName, basicProperties, message.getBytes("UTF-8"));
            }else{
                logger.info("目标队列:{};发送内容:{}",queueName,message );
                rabbitTemplate.convertAndSend(queueName,message);
            }
        } catch (IOException e) {
            logger.error("业务异常",e);
        } finally{
            try {
                channel.close();
                connection.close();
            } catch ( TimeoutException e) {
                logger.error("业务异常",e);
            }catch (IOException e){
                logger.error("业务异常",e);
            }

        }

    }

}
